"""
电力系统故障检测模块
用于检测单相接地、双相接地和三相故障
"""

from typing import Dict

import pandas as pd

from Analyzer.RMSAnalyzer import RMSAnalyzer
from Detector.FaultStartTimeDetector import FaultStartTimeDetector
from Detector.FaultTypeDetector import FaultTypeDetector
from Processor.WaveletProcessor import WaveletProcessor
from model.FaultDetectionConfig import FaultDetectionConfig
from model.FaultDetectionResult import FaultTypeResult


class FaultDetectionSystem:
    """故障检测系统主类"""

    def __init__(self, config: FaultDetectionConfig):
        self.config = config
        self.rms_analyzer = RMSAnalyzer(config)
        self.fault_type_detector = FaultTypeDetector()
        self.wavelet_processor = WaveletProcessor(config)
        self.fault_time_detector = FaultStartTimeDetector()


    def extract_rms_values(self, df: pd.DataFrame, t_center: pd.Timestamp) -> Dict:
        """提取RMS值"""
        return self.rms_analyzer.extract_multi_cycle_rms(df, t_center)

    def detect_fault_type(self, df: pd.DataFrame, cfg_obj) -> FaultTypeResult:
        """
        检测故障类型
        """
        # Step 1: 数据预处理（可选小波去噪）
        if self.config.use_wavelet and self.wavelet_processor:
            df_processed = df.copy()
            for col in df.columns:
                if col not in ['Freq'] and col in df.columns:
                    df_processed[col] = self.wavelet_processor.denoising(df[col])
        else:
            df_processed = df

        t_fault = self.fault_time_detector.detect(df_processed, cfg_obj)

        f_results = self.fault_type_detector.detect(df_processed, t_fault, cfg_obj)

        f_results.details['RMS'] = self.extract_rms_values(df_processed, t_fault)

        return f_results

